const db = require('../config/database');
const { successResponse, errorResponse } = require('../utils/response');

/**
 * 记录游戏结果
 */
const recordGameResult = async (req, res) => {
    const connection = await db.getConnection();
    
    try {
        await connection.beginTransaction();
        
        const userId = req.user.id;
        const { gameType, score, correctCount, wrongCount, duration } = req.body;
        
        // 验证游戏类型
        const validGameTypes = ['match', 'rain', 'puzzle', 'monopoly', 'pronunciation'];
        if (!validGameTypes.includes(gameType)) {
            return errorResponse(res, '无效的游戏类型', 400);
        }
        
        // 插入游戏记录
        await connection.execute(
            `INSERT INTO game_records (user_id, game_type, score, correct_count, wrong_count, duration)
             VALUES (?, ?, ?, ?, ?, ?)`,
            [userId, gameType, score, correctCount || 0, wrongCount || 0, duration || 0]
        );
        
        // 根据分数奖励星星
        let starsReward = Math.floor(score / 100);
        if (starsReward > 0) {
            await connection.execute(
                'UPDATE users SET stars = stars + ? WHERE id = ?',
                [starsReward, userId]
            );
        }
        
        // 更新宠物经验
        const expReward = Math.floor(score / 10);
        await connection.execute(
            `UPDATE pets 
             SET exp = exp + ?,
                 level = FLOOR(1 + SQRT((exp + ?) / 100))
             WHERE user_id = ?`,
            [expReward, expReward, userId]
        );
        
        // 更新每日任务
        await connection.execute(
            'CALL update_daily_task(?, ?)',
            [userId, 'play_game']
        );
        
        await connection.commit();
        
        return successResponse(res, {
            starsReward,
            expReward
        }, '游戏结果已保存');
        
    } catch (error) {
        await connection.rollback();
        console.error('记录游戏结果错误:', error);
        return errorResponse(res, '记录游戏结果失败', 500, error);
    } finally {
        connection.release();
    }
};

/**
 * 获取游戏历史记录
 */
const getGameHistory = async (req, res) => {
    try {
        const userId = req.user.id;
        const { gameType, limit = 10 } = req.query;
        
        let query = 'SELECT * FROM game_records WHERE user_id = ?';
        const params = [userId];
        
        if (gameType) {
            query += ' AND game_type = ?';
            params.push(gameType);
        }
        
        query += ' ORDER BY played_at DESC LIMIT ?';
        params.push(parseInt(limit));
        
        const [records] = await db.execute(query, params);
        
        return successResponse(res, records);
        
    } catch (error) {
        console.error('获取游戏历史错误:', error);
        return errorResponse(res, '获取游戏历史失败', 500, error);
    }
};

/**
 * 获取游戏排行榜
 */
const getGameLeaderboard = async (req, res) => {
    try {
        const { gameType, period = 'all', limit = 10 } = req.query;
        
        if (!gameType) {
            return errorResponse(res, '请指定游戏类型', 400);
        }
        
        let query = `
            SELECT 
                u.id,
                u.username,
                u.school,
                u.grade,
                u.avatar,
                MAX(gr.score) as best_score,
                COUNT(*) as games_played
            FROM game_records gr
            INNER JOIN users u ON gr.user_id = u.id
            WHERE gr.game_type = ?
        `;
        const params = [gameType];
        
        // 时间筛选
        if (period === 'week') {
            query += ' AND gr.played_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)';
        } else if (period === 'month') {
            query += ' AND gr.played_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)';
        }
        
        query += ' GROUP BY u.id ORDER BY best_score DESC LIMIT ?';
        params.push(parseInt(limit));
        
        const [leaderboard] = await db.execute(query, params);
        
        return successResponse(res, leaderboard);
        
    } catch (error) {
        console.error('获取游戏排行榜错误:', error);
        return errorResponse(res, '获取游戏排行榜失败', 500, error);
    }
};

/**
 * 获取随机单词（用于游戏）
 */
const getRandomWords = async (req, res) => {
    try {
        const userId = req.user.id;
        const { count = 10, grade, difficulty } = req.query;
        
        // 获取用户年级
        const [users] = await db.execute('SELECT grade FROM users WHERE id = ?', [userId]);
        const userGrade = users[0].grade;
        
        const { getGradesUpTo } = require('../utils/gradeLevel');
        
        // 根据难度模式决定年级范围
        let allowedGrades = [];
        if (difficulty === 'easy') {
            // 简单模式：只包含当前年级
            allowedGrades = [grade || userGrade];
        } else if (difficulty === 'medium') {
            // 中等模式：当前及上一学期
            const gradeList = ['三上', '三下', '四上', '四下', '五上', '五下', '六上', '六下'];
            const currentIndex = gradeList.indexOf(grade || userGrade);
            if (currentIndex === -1) {
                allowedGrades = [userGrade];
            } else if (currentIndex === 0) {
                allowedGrades = [gradeList[0]];
            } else {
                allowedGrades = [gradeList[currentIndex - 1], gradeList[currentIndex]];
            }
        } else {
            // 挑战模式（hard或未指定）：当前年级及以下所有年级
            allowedGrades = getGradesUpTo(grade || userGrade);
        }
        
        console.log('🎮 游戏加载单词 - 用户年级:', userGrade, '难度:', difficulty || 'hard', '允许年级:', allowedGrades);
        
        let query = `
            SELECT v.*, up.mastery_level
            FROM vocabulary v
            LEFT JOIN user_progress up ON v.id = up.word_id AND up.user_id = ?
            WHERE v.grade IN (${allowedGrades.map(() => '?').join(',')})
        `;
        const params = [userId, ...allowedGrades];
        
        // 难度筛选
        if (difficulty === 'easy') {
            query += ' AND (up.mastery_level >= 60 OR up.mastery_level IS NULL)';
        } else if (difficulty === 'medium') {
            query += ' AND (up.mastery_level BETWEEN 30 AND 60 OR up.mastery_level IS NULL)';
        } else if (difficulty === 'hard') {
            query += ' AND (up.mastery_level < 30 OR up.mastery_level IS NULL)';
        }
        
        // 使用字符串拼接处理LIMIT，避免参数类型问题
        const countNum = Math.min(Math.max(1, parseInt(count) || 10), 100);
        query += ` ORDER BY RAND() LIMIT ${countNum}`;
        
        const [words] = await db.execute(query, params);
        
        return successResponse(res, words);
        
    } catch (error) {
        console.error('获取随机单词错误:', error);
        return errorResponse(res, '获取随机单词失败', 500, error);
    }
};

module.exports = {
    recordGameResult,
    getGameHistory,
    getGameLeaderboard,
    getRandomWords
};

